#include <stdio.h>
#include <stdlib.h>

const char HELP_DOC[] = \
	"format: prime_sum MIN MAX \n" \
	"-h help \n" \
	"Bugs included. \n";

#define  true 1
#define false 0
#define TEST false

typedef unsigned char bool;

int main(int argc, char **argv){
	if (argc == 1){
	//no argument passed in
		printf(HELP_DOC);
		exit(0);
	}
	else{
		printf("The arguments you passed in is: \n");
		for (int i=1; i<argc; i++) {
			printf(argv[i]);
			printf("\n");
		}
	}
	
	int min_n = atoi(argv[1]);
	int max_n = atoi(argv[2]);
	int arr_size = sizeof(int) * (max_n - min_n);
	printf("min: %d, max: %d, size: %d\n", min_n, max_n, arr_size);
	int *arr  = calloc(max_n - min_n, sizeof(int));
	if (arr == NULL){
		printf("error occured");
		exit(1);
	}

	printf("addr of arr: %p\n", arr);
	find_primes(min_n, max_n, arr);	
	int *p_tmp = arr;
	int sum = 0;
	while (!*p_tmp){
		sum += *p_tmp;
		p_tmp++;
	}
	free(arr);
	printf("Primes sum: %d\n", sum);
}

int find_primes(int min_n, int max_n, int rlst[]) {
	int *p_ognRlst = rlst;
	bool is_prime = false;
	printf("p_ognRlst: %p\n", p_ognRlst);
	printf("rlst: %p\n", rlst);

	for (int i=min_n; i<=max_n; i++) {
		is_prime = true;  //assume it is a prime
		for (int j=2; j<i; j++) {
			if (i%j == 0){ //a bug's here, let it go
				is_prime = false;
				break;
			}
		}

		if (is_prime) {
			*rlst = i;
			rlst++;
			if (TEST) {
				printf("i:%d, found: %d, addr:%p\n",i, *(rlst-1), rlst);
			}
		}
	}
	
	printf("p_ognRlst: %p\n", p_ognRlst);
	printf("rlst: \t\t%p\n", rlst);
	rlst = p_ognRlst;
	printf("rlst: \t\t%p\n", rlst);
	if (TEST) {
		printf("\nmax: %d, min:%d\n found primes:\n", max_n, min_n);
		while (*(rlst++)){
			printf("%d ",*rlst);
		}
	}	
}

void debug(char *str){
	if (TEST) {
		printf(str);
	}
}
